package com.bw.module_main

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.lib_common.arouter.Router
import com.bw.lib_common.base.BaseActivity
import com.bw.module_main.databinding.ActivityMainBinding
import com.bw.module_main.ui.MainViewModel
import dagger.hilt.android.AndroidEntryPoint



@AndroidEntryPoint
@Route(path = Router.Ui.MainActivity)
class MainActivity : BaseActivity<MainViewModel,ActivityMainBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_main

    // 用于缓存 Fragment 实例（键：tag，值：Fragment 实例）
    private val fragmentCache = mutableMapOf<String, Fragment>()

    companion object{
        private const val HOME_FRAGMENT_TAG = "home"
        private const val SERVICE_FRAGMENT_TAG = "service"
    }



    override fun initView() {
        // 初始化默认显示首页
        navToFragment(R.id.nav_home)
        // 初始化 RadioButton 选中状态
        // 设置初始选中项（首页）
        mBinding.navHome.isChecked = true
        // 给 RadioGroup 添加选中监听
        mBinding.rgBottom.setOnCheckedChangeListener { _, checkedId ->
            navToFragment(checkedId)
        }
    }



    private fun navToFragment(id:Int) {
    val bt = supportFragmentManager.beginTransaction()
    hideCurrentFragment(bt) // 先隐藏所有 Fragment

    val (routerPath, tag) = when (id) {
        R.id.nav_home -> Router.Ui.HomeFragment to HOME_FRAGMENT_TAG
        R.id.nav_service -> Router.Ui.ServiceFragment to SERVICE_FRAGMENT_TAG
        R.id.nav_message -> Router.Ui.MessageFragment to "message" // 直接用字符串（需与缓存键一致）
        R.id.nav_announcement -> Router.Ui.AnnouncementFragment to "announcement"
        R.id.nav_mine -> Router.Ui.MineFragment to "mine"
        else -> return // 无效 ID，直接返回
    }

    // 从缓存中获取 Fragment，不存在则通过 ARouter 创建并缓存
    val fragment = fragmentCache.getOrPut(tag) {
        ARouter.getInstance().build(routerPath).navigation(this) as Fragment
    }

    // 处理 Fragment 的显示/添加逻辑
    if (fragment.isAdded) {
        bt.show(fragment) // 已添加则显示
    } else {
        bt.add(R.id.fragment_container, fragment, tag) // 未添加则添加到容器
    }

    bt.commitAllowingStateLoss() // 提交事务
}

    /**
     * 获得未读消息红点更新显示
     */
    private fun updateUnreadMessage() {

    }


  private fun hideCurrentFragment(bt: FragmentTransaction) {
    // 遍历所有缓存的 Fragment，隐藏已添加的实例
    fragmentCache.values.forEach { fragment ->
        if (fragment.isAdded) { // 确保 Fragment 已添加到容器
            bt.hide(fragment)
        }
    }
  }




}